"""
Second Life login utilties.
"""

import md5
import random
import string
import xmlrpclib

from django.contrib.auth.models import User

AUTH_URL = 'https://login.agni.lindenlab.com/cgi-bin/login.cgi'

def random_password_str():
    """
    Return a random string to fill a password field.

    This is not meant to be an actual password, just a hard
    to crack place holder.
    """
    placeholder = '%s%s' % (random.random(),
                              ''.join(random.sample(string.letters, 10)))
    return md5.new(placeholder).hexdigest()

def random_prefix_str():
    """
    Returns a random string to prefix before usernames.
    """
    return 'SL_%s' % ''.join(random.sample(string.letters, 4))
    
def get_or_create_sl_user(first, last):
    """
    Get or create a Django user for the given Second Life user.

    Django usernames are not used when authenticating via
    Second Life login, but the User class requires a unique
    username for each user. A duplicate *could* happen since we
    concatenate first and last names and limit to 30 characters,
    so add a unique prefix to each username to avoid
    possible duplicate usernames.
    """
    try:
        user = User.objects.get(first_name=first, last_name=last)
    except User.DoesNotExist:
        username = '%s_%s%s' % (random_prefix_str(), first, last)
        user = User(username=username[:30], password=random_password_str(),
                    first_name=first, last_name=last)
        user.is_staff = False
        user.is_superuser = False
        user.save()
    return user

def sl_login(first, last, password):
    """
    Returns the response from an SL login attempt.

    Login details doesn't seem to require accurate values
    for "mac" and "view_digest" so just stuff anything in
    there for now.
    """
    password_md5 = '$1$' + md5.new(password).hexdigest()
    s = xmlrpclib.ServerProxy(AUTH_URL)
    login_details = {
        'first': first,
        'last': last,
        'passwd': password_md5,
        'start': 'last',
        'major': '1',
        'minor': '19',
        'patch': '0',
        'build': '5',
        'platform': 'Lin',
        'mac': '',
        'options': [],
        'user-agent': 'SLDjangoAuthBackend 0.1',
        'id0': '',
        'agree_to_tos': '',
        'viewer_digest': ''
    }
    response = s.login_to_simulator(login_details)
    return response

def valid_sl_login(first, last, password):
    """
    Returns True if the Second Life user is authenticated.
    """
    response = sl_login(first, last, password)
    if response['login'] == 'true':
        return True
    return False
